<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Constants\ErrorCode;
use App\Model\Admin\Admin;
use App\Model\BalanceOrder;
use App\Model\Bill;
use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\DevicePort;
use App\Model\Order;
use App\Model\RefundBalanceLog;
use App\Model\RefundHistory;
use App\Model\RefundLog;
use App\Model\Station;
use App\Model\User;
use App\Services\BankService;
use App\Services\Bolai\PackService;
use App\Services\DeviceService;
use App\Services\Iot\IotService1 as IotService;
use App\Services\PaymentStrategyFactory;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class OrderController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Order $order;

    #[Inject]
    protected BalanceOrder $balanceOrder;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }


    /**导出订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportOrder(RequestInterface $request)
    {
        $page = $request->inputs(['page', 'limit', 'address', 'out_ord_id', 'number', 'distributor_id',
            'keyword', 'sn', 'time', 'payment_type', 'dis_phone', 'station_id',
            'status', 'min_power', 'max_power', 'channel_number']);
        $page['info'] = $this->admin->getInfo($request);
        $model = Order::query()
            ->where(function ($query) use ($page) {
                if ($page['distributor_id']) {
                    $query->where('distributor_id', $page['distributor_id']);
                } else {
                    if (isset($page['info']['distributor_id'])) {
                        $query->where('distributor_id', $page['info']['distributor_id']);
                    }
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['station_id']) {
                    if (!is_array($page['station_id'])) {
                        $page['station_id'] = json_decode($page['station_id'], true);
                    }
                    $query->whereIn('station_id', $page['station_id']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['out_ord_id']) {
                    $query->where('out_ord_id', $page['out_ord_id']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['payment_type']) {
                    $query->where('payment_type', $page['payment_type']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['sn']) {
                    $query->where('sn', $page['sn']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['status']) {
                    $query->where('status', $page['status']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['min_power']) {
                    $query->where('power', '>=', $page['min_power']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['max_power']) {
                    $query->where('power', '<=', $page['max_power']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['channel_number']) {
                    $query->where('channel_number', $page['channel_number'] - 1);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['keyword']) {
                    $query->where('number', $page['keyword']);
                }
            })
            ->where(function ($query) use ($page) {
                if ($page['number']) {
                    $query->where('number', $page['number']);
                }
            })
            ->where(function ($query) use ($page) {
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('created_at', '>=', $page['time'][0]);
                    $query->where('created_at', '<=', $page['time'][1]);
                }
            })
//                ->when($page['phone'] ?? null, function ($query) use ($page) {
//                    $query->whereHas('user', function ($subQuery) use ($page) {
//                        $subQuery->where('phone', $page['phone']);
//                    });
//                })
            // 新增 dis_phone 搜索 distributor 表
            ->when($page['dis_phone'] ?? null, function ($query) use ($page) {
                $query->whereHas('distributor', function ($subQuery) use ($page) {
                    $subQuery->where('phone', $page['dis_phone']);
                });
            })
            ->with([
                'station' => function ($query) use ($page) {
                    $query->where(function ($query) use ($page) {
                        if ($page['address']) {
                            $query->where('address', '%' . $page['address'] . '%');
                        }
                    });
                },
            ])
            ->with(['user' => function ($query) {
                $query->select('id', 'nickname');
            }])
            ->with(['distributor' => function ($query) {
                $query->select('id', 'mobile', 'name');
            }]);
        $data['list'] = $model
            ->orderByDesc('id')
            ->get();
        try {
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // 设置 Excel 文档的头部
            $sheet->setCellValue('A1', '订单号');
            $sheet->setCellValue('B1', '经销商');
            $sheet->setCellValue('C1', '开始时间');
            $sheet->setCellValue('D1', '结束时间');
            $sheet->setCellValue('E1', '服务费/元');
            $sheet->setCellValue('F1', '实付金额/元');
            $sheet->setCellValue('G1', '退款金额/元');
            $sheet->setCellValue('H1', '实付电费/元');
            $sheet->setCellValue('I1', '是否使用券');
//        $sheet->setCellValue('J1', '交易单号');
            $sheet->setCellValue('J1', '电站名称');
            $sheet->setCellValue('K1', '设备号' . ' ');
            $sheet->setCellValue('L1', '端口');
            $sheet->setCellValue('M1', '支付类型');
            $sheet->setCellValue('N1', '停止原因');
            foreach (range('A', 'N') as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }
// 设置单元格水平居中的样式数组配置
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];

// 应用样式到第一行的A到O列
            $sheet->getStyle('A:N')->applyFromArray($styleArray);
            // 从第二行开始填充订单数据
            $row = 2;
            foreach ($data['list'] as $order) {
                switch ($order->payment_type) {
                    case '1':
                        $order->payment_type = '微信';
                        break;
                    case '3':
                        $order->payment_type = '余额';
                        break;
                    case '2':
                        $order->payment_type = '支付宝';
                        break;
                    case '4':
                        $order->payment_type = '刷卡';
                        break;
                    case '5':
                        $order->payment_type = '直充';
                        break;
                    default:
                        $order->payment_type = '白名单';
                        break;
                }
                switch ($order->status) {
                    case '1':
                        $order->status = '已支付';
                        break;
                    case '0':
                        $order->status = '未支付';
                        break;
                    case '2':
                        $order->status = '使用中';
                        break;
                    case '4':
                        $order->status = '已结束';
                        break;
                    case '5':
                        $order->status = '已退款';
                        break;
                    default:
                        $order->status = '失败';
                        break;
                }
                $sheet->setCellValue('A' . $row, $order->number . ' ');
                $sheet->setCellValue('B' . $row, $order->distributor->name);
                $sheet->setCellValue('C' . $row, $order->estimate_stop_at);
                $sheet->setCellValue('D' . $row, $order->stop_at);
                $sheet->setCellValue('E' . $row, $order->service_fee);
                $sheet->setCellValue('F' . $row, $order->fee);
                $sheet->setCellValue('G' . $row, $order->return_fee);
                $sheet->setCellValue('H' . $row, $order->power_fee);
                if ($order->coupon_record_id) {
                    $sheet->setCellValue('I' . $row, '是');
                } else {
                    $sheet->setCellValue('I' . $row, '否');
                }
//            $sheet->setCellValue('J' . $row, $order['out_ord_id'].' ');
                $sheet->setCellValue('J' . $row, $order->station->name);
                $sheet->setCellValue('K' . $row, $order->sn);
                $sheet->setCellValue('L' . $row, $order->channel_number + 1);
                $sheet->setCellValue('M' . $row, $order->payment_type);
                $sheet->setCellValue('N' . $row, $order->stop_reason);
                $sheet->setCellValue('O' . $row, $order->status);
                $row++;
            }
            // 将 Spreadsheet 对象写入 XLSX 文件
            $writer = new Xlsx($spreadsheet);
            // 创建临时文件
            $publicPath = BASE_PATH . '/public/upload/xls/';
            $fileName = date('YmdHis', time()) . '-orders.xlsx';
//        $temp_file = tempnam(sys_get_temp_dir(), $fileName);
            $temp_file = $publicPath . $fileName;
            // 保存到临时文件
            $writer->save($temp_file);
            return $this->success(['url' => Common::MAIN_HOST . '/upload/xls/' . $fileName]);
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage());
        }

    }

    /**
     * 订单列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface|RedisException
     */
    public function getList(RequestInterface $request): ResponseInterface
    {
        try {
            $page = $request->inputs(['page', 'limit', 'address', 'out_ord_id', 'number', 'distributor_id',
                'keyword', 'sn', 'time', 'payment_type', 'dis_phone', 'station_id',
                'status', 'min_power', 'max_power', 'channel_number']);
            $page['info'] = $this->admin->getInfo($request);
            $model = Order::query()
                ->where(function ($query) use ($page) {
                    if ($page['distributor_id']) {
                        $distributor  = $this->distributors->find($page['distributor_id']);
                        if ($distributor->level == 1) {
                            $distributors = $this->distributors->where('parent_id', $page['distributor_id'])
                                ->orWhere('id', $page['distributor_id'])->pluck('id');
                            $query->whereIn('distributor_id', $distributors);
                        }else{
                            $query->where('distributor_id', $page['distributor_id']);
                        }
                    } else {
                        if (isset($page['info']['distributor_id'])) {
                            $distributor = $this->distributors->find($page['info']['distributor_id']);
                            if ($distributor->level == 1) {
                                $distributors = $this->distributors->where('parent_id', $page['info']['distributor_id'])
                                    ->orWhere('id', $page['info']['distributor_id'])->pluck('id');
                                $query->whereIn('distributor_id', $distributors);
                            }
                            $query->where('distributor_id', $page['info']['distributor_id']);
                        }
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['station_id']) {
                        if (!is_array($page['station_id'])) {
                            $page['station_id'] = json_decode($page['station_id'], true);
                        }
                        $query->whereIn('station_id', $page['station_id']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['out_ord_id']) {
                        $query->where('out_ord_id', $page['out_ord_id']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['payment_type']) {
                        $query->where('payment_type', $page['payment_type']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['sn']) {
                        $query->where('sn', $page['sn']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['status']) {
                        $query->where('status', $page['status']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['min_power']) {
                        $query->where('power', '>=', $page['min_power']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['max_power']) {
                        $query->where('power', '<=', $page['max_power']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['channel_number']) {
                        $query->where('channel_number', $page['channel_number'] - 1);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['keyword']) {
                        $query->where('number', $page['keyword']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if ($page['number']) {
                        $query->where('number', $page['number']);
                    }
                })
                ->where(function ($query) use ($page) {
                    if (isset($page['time']) && is_array($page['time'])) {
                        $query->where('created_at', '>=', $page['time'][0]);
                        $query->where('created_at', '<=', $page['time'][1]);
                    }
                })
//                ->when($page['phone'] ?? null, function ($query) use ($page) {
//                    $query->whereHas('user', function ($subQuery) use ($page) {
//                        $subQuery->where('phone', $page['phone']);
//                    });
//                })
                // 新增 dis_phone 搜索 distributor 表
                ->when($page['dis_phone'] ?? null, function ($query) use ($page) {
                    $query->whereHas('distributor', function ($subQuery) use ($page) {
                        $subQuery->where('phone', $page['dis_phone']);
                    });
                })
                ->with([
                    'station' => function ($query) use ($page) {
                        $query->where(function ($query) use ($page) {
                            if ($page['address']) {
                                $query->where('address', '%' . $page['address'] . '%');
                            }
                        });
                    },
                ])
                ->with(['user' => function ($query) {
                    $query->select('id', 'nickname');
                }])
                ->with('detail')
                ->with(['distributor' => function ($query) {
                    $query->select('id', 'mobile', 'name');
                }]);
            $data['total'] = $model->count();
            $data['list'] = $model
                ->orderByDesc('id')
                ->offset(($page['page'] - 1) * $page['limit'])
                ->limit($page['limit'])
                ->get();
            return $this->success($data);
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage() . $e->getTraceAsString());
        }
    }


    /**余额充值订单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function balanceList(RequestInterface $request): ResponseInterface
    {
        $page = $request->inputs(['page', 'limit', 'out_ord_id', 'nickname'
            , 'number', 'time', 'payment_type',
            'status']);
        $query = Db::table('balance_orders as o')
            ->leftJoin('users as u', 'o.user_id', '=', 'u.id')
            ->where(function ($query) use ($page) {
                if (array_key_exists('keyword', $page) && $page['keyword']) {
                    $query->where('o.number', 'like', '%' . $page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
                }
                if ($page['nickname']) {
                    $query->where('u.nickname', $page['nickname']);
                }
                if ($page['out_ord_id']) {
                    $query->where('o.out_ord_id', $page['out_ord_id']);
                }
                if ($page['payment_type']) {
                    $query->where('o.payment_type', $page['payment_type']);
                }
                if ($page['status']) {
                    $query->where('o.status', $page['status']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('o.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit']);
        $data['total'] = $query->count();
        $data['list'] = $query->select('o.*', 'u.nickname', 'u.phone')
            ->get();
        return $this->success($data);
    }


    /**下拉菜单-套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectCharge(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $distributor_id = $request->input('distributor_id');
        $list = $this->chargeOption->where('distributor_id', 0)->orderBy('sort', 'desc')
            ->get(['id', 'name'])->toArray();
        foreach ($list as $k => $v) {
            $list[$k]['name'] = '[默认]' . $v['name'];
        }
        if ($distributor_id) {
            $distributor_id = json_decode($distributor_id);
            if (count($distributor_id) > 0) {
                $distributor_id = end($distributor_id);
                $dis_list = $this->chargeOption->where('distributor_id', $distributor_id)->orderBy('sort', 'desc')
                    ->get(['id', 'name'])->toArray();
                $list = array_merge($list, $dis_list);
            }
        }
        return $this->success($list);
    }

    /**下拉菜单充电桩
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function selectStation(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $distributor_id = $request->input('distributor_id');
        if (!$distributor_id) {
            return $this->error(code: 1001, msg: '请先选择经销商');
        }
        $distributor_id = json_decode($distributor_id);
        if (is_array($distributor_id)) {
            if (count($distributor_id) > 0) {
                $distributor_id = end($distributor_id);
            }
        }
        $list = $this->station->where('distributor_id', $distributor_id)
            ->get(['id', 'name'])->toArray();
        return $this->success($list);
    }

    /**修改状态
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function changeStatus(RequestInterface $request): ResponseInterface
    {
        $status = $request->input('status', 0, 'int');
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(code: 1001, msg: '缺失参数id');
        }
        $this->station->where('id', $id)->update(['is_active' => $status]);
        return $this->success(msg: '修改成功');
    }


    public function getDetail(RequestInterface $request)
    {
        $orderId = $request->input('order_id');
        $order = $this->order->where('id', $orderId)
            ->with('detail')->first();
        return $this->success($order);
    }


    /**获取经销商id
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getDistributor(RequestInterface $request): ResponseInterface
    {
        $station_id = $request->input('station_id', 0, 'int');
        $distributorId = $this->station->where('id', $station_id)->first(['distributor_id']);
        return $this->success($distributorId);
    }


    /**创建电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function create(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $data = $request->post();
        if (!$data['distributor_id']) {
            $data['distributor_id'] = 0;
        }
        if ($data['images']) {
            $data['images'] = json_encode($data['images']);
        }
        if (array_key_exists('id', $data) && $data['id'] > 0) {
            $id = $data['id'];
            unset($data['id']);
            if (isset($data['distributor_name'])) {
                unset($data['distributor_name']);
            }
            if (isset($data['device_num'])) {
                unset($data['device_num']);
            }
            if (is_array($data['distributor_id'])) {
                $data['distributor_id'] = end($data['distributor_id']);
            }
            if (array_key_exists('updated_at', $data)) {
                unset($data['updated_at']);
            }
            $this->station->where('id', $id)->update($data);
        } else {
            $data['distributor_id'] = end($data['distributor_id']);
            Station::create($data);
        }
        return $this->success();
    }

    /**删除充电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function del(RequestInterface $request): \Psr\Http\Message\ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $this->station->where('id', $id)->delete();
        return $this->success();
    }


    /**关闭订单并结束充电
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function stopOrder(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        $type = $request->input('type', 1, 'int');
        $orderModel = $this->order->with('device')->find($id);
        if (!$orderModel) {
            return $this->error('订单不存在');
        }
        if ($type == 1) {
            $orderModel->duration_seconds = $orderModel->getDurationSeconds();
            $orderModel->save();
            $data = [
                'fd' => $orderModel->device->fd,
                'sn' => $orderModel->device->sn,
                'channel_number' => $orderModel->channel_number,
                'number' => $orderModel->number,
                'balance' => 0
            ];
            $response = DeviceService::postTcp('/tcp/stop', $data);
            $responseData = json_decode($response->getBody()->getContents(), true);
            if ($response->getStatusCode() == 200) {
                if ($responseData['code'] == 200) {
                    Db::commit();
                    return $this->success(msg: '结束成功');
                } else {
                    Db::rollBack();
                    return $this->error(1001, $responseData['msg'] ?? '关闭发送失败');
                }
            } else {
                Db::rollBack();
                return $this->error(1001, '关闭发送失败: ' . ($responseData['message'] ?? '未知错误'));
            }
        } else {
            $orderModel->offStop('设备离线结单');
            return $this->success(msg: '结束成功');
        }
    }


    /**
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function refundService(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        $orderModel = $this->order->find($id);
        if ($orderModel->service_fee > 0) {
            $orderModel->serviceRefund();
        }
        return $this->success();
    }


    /**获取退款记录
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getRefundList(RequestInterface $request): ResponseInterface
    {
        $number = $request->input('number');
        $list = RefundLog::where('number', $number)
            ->get();
        return $this->success($list);
    }


    public function balanceRefundList(RequestInterface $request): ResponseInterface
    {
        $number = $request->input('number');
        $list = RefundBalanceLog::where('number', $number)
            ->get();
        return $this->success($list);
    }

    public function refundBalance(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        $fee = $request->input('fee', 0);
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        if ($fee <= 0) {
            return $this->error(1002, '参数错误');
        }
        $orderModel = $this->balanceOrder->find($id);
        $result = $orderModel->refundOrder($fee);
        return $this->success($result);
    }

    /**退款
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function refundNormal(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        $fee = $request->input('fee', 0);
        $type = $request->input('type', 2, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        if ($fee <= 0) {
            return $this->error(1002, '参数错误');
        }
        $orderModel = $this->order->find($id);
        if($type == 3){
            $check = RefundLog::where('number',$orderModel->number)
                ->where('type',3)
                ->where('status',1)->first();
            if($check){
                return $this->error(1002,'该订单已退款安心充，请勿重复操作');
            }
            $fee = $orderModel->service_fee;
        }
        $result = $orderModel->refundOrder($fee,$type);
        return $this->success($result);
    }




    /**取消抽单
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function cancelDraw(RequestInterface $request): ResponseInterface
    {
        $id = $request->input('id', 0, 'int');
        if (!$id) {
            return $this->error(ErrorCode::PARAMS_ERR);
        }
        try {
            $orderModel = $this->order->find($id);
            $orderModel->save();
            if ($orderModel->status == Order::STATUS_END || $orderModel->status == Order::STATUS_REFUNDED) {
                $orderModel->distributorSettle();
                $orderModel->feeStatics();
            }
            return $this->success(msg: '取消抽单成功');
        } catch (\Exception $e) {
            return $this->error(1001, $e->getMessage());
        }
    }
}
